package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.pojo.LogRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * @Author lenny
 * @create 2021/9/17 22:29
 */

@Service(version = "1.0.0")
public class BackgroundDashboardApiImpl implements BackgroundDashboardApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 统计用户.月.周. 活跃数
     *
     * @param defaultTime   设置的当天(此刻当晚)晚上0点
     * @param appointedTime 时间段,30,7,1,0
     * @return
     */
    @Override
    public Integer activeUserNum(Long defaultTime, Long appointedTime) {

        /*
         * 糊涂工具包
         * 获取指定日期偏移指定时间后的时间，生成的偏移日期不影响原日期
         *
         * @param date      基准日期
         * @param dateField 偏移的粒度大小（小时、天、月等）{@link DateField}
         * @param offset    偏移量，正数为向后偏移，负数为向前偏移
         * @return 偏移后的日期
         *
         *  "这个 日志表 只对'登陆'  进行记录 "
         */
        Query query = Query.query(Criteria.where("logTime").lte(defaultTime).gte(appointedTime));
        List<LogRecord> logRecords = mongoTemplate.find(query, LogRecord.class);

        Set<LogRecord> hashSet = new HashSet<>();

        for (LogRecord logRecord : logRecords) {
            hashSet.add(logRecord);
        }

        return hashSet.size();
    }

    /**
     * 今日活跃用户
     *
     * @param defaultTime
     * @param nowTime
     * @return
     */
    @Override
    public Integer todayActiveUserNum(Long defaultTime, Long nowTime) {

        Query query = Query.query(Criteria.where("logTime").lte(nowTime).gte(defaultTime));
        List<LogRecord> logRecords = mongoTemplate.find(query, LogRecord.class);

        Set<Long> treeSet = new TreeSet<>();
        for (LogRecord logRecord : logRecords) {
            treeSet.add(logRecord.getUserId());
        }
        return treeSet.size();
    }


    /**
     * 今日'新增用户'涨跌率
     *
     * @param newUsersToday
     * @param newUsersYesterday
     * @return
     */
    @Override
    public Integer newUserAmplitude(Integer newUsersToday, Integer newUsersYesterday) {

        double today = (double) newUsersToday;
        double yesterday = (double) newUsersYesterday;

        double amplitude = 0.0;
        if (yesterday != 0) {
            double rate = (today - yesterday) / yesterday;
            amplitude = (double) (Math.round(rate * 100)) / 100;
        } else {
            amplitude = 0.0;
        }

        return (int) (amplitude * 100);
    }


    /**
     * 今日'活跃用户'涨跌率
     *
     * @param todayUsers
     * @param yesterdayUsers
     * @return
     */
    @Override
    public Integer activeUserAmplitude(Integer todayUsers, Integer yesterdayUsers) {
        double activeToday = (double) todayUsers;
        double activeYesterday = (double) yesterdayUsers;

        double amplitude = 0.0;
        if (activeYesterday != 0) {
            double rate = (activeToday - activeYesterday) / activeYesterday;
            amplitude = (double) (Math.round(rate * 100)) / 100;
        } else {
            amplitude = 0.0;
        }

        return (int) (amplitude * 100);
    }

    /**
     * 今日登录次数
     *
     * @param defaultTime
     * @param nowTime
     * @return
     */
    @Override
    public Integer loginCount(long defaultTime, long nowTime) {
        Query query = Query.query(Criteria.where("logTime").lte(nowTime).gte(defaultTime));
        long loginCount = mongoTemplate.count(query, LogRecord.class);

        return (int) loginCount;

    }

    /**
     * 昨日(之前)登录次数
     *
     * @param defaultTime
     * @param dayTime
     * @return
     */
    @Override
    public Integer loginCountBefore(long defaultTime, long dayTime) {

        Query query = Query.query(Criteria.where("logTime").lte(defaultTime).gte(dayTime));
        long loginCount = mongoTemplate.count(query, LogRecord.class);

        return (int) loginCount;

    }



    /**
     * 查询活跃用户(按照每一天的)
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Integer queryActiveUserCountByDate(long startTime, long endTime) {
        Query query =Query.query(Criteria.where("logTime").gte(startTime).lte(endTime));
        List<LogRecord> distinct = mongoTemplate.findDistinct(query, "userId", "LogRecord", LogRecord.class);
        return distinct.size();

    }

    @Override
    public List<LogRecord> queryNextDayLeft(long startTime, long endTime) {
        Query query =Query.query(Criteria.where("logTime").gte(startTime).lte(endTime));
        return mongoTemplate.findDistinct(query, "userId", "LogRecord", LogRecord.class);
    }

    /**e
     * 过去七天平均使用时长(用户平均)
     *
     * @param defaultTime
     * @param weekTime
     * @return
     */
    @Override
    public Integer averageUseTime(long defaultTime, long weekTime) {
        Query query = Query.query(Criteria.where("logTime").lte(defaultTime).gte(weekTime));
        List<LogRecord> logRecords = mongoTemplate.find(query, LogRecord.class);
        //总使用时长
        //long totalTime = 0;
        //for (LogRecord logRecord : logRecords) {
        //    Long useTime = logRecord.getUseTime();
        //    totalTime += useTime;
        //}
        ////用户数
        //Set<LogRecord> hashSet = new HashSet<>();
        //hashSet.addAll(logRecords);
        //int userCount = hashSet.size();
        //
        ////平均使用时长,此时为ms,换算成秒
        ////TODO
        //int averageTime = (int) totalTime  ;

        //return averageTime;

        return 7;

    }


}
